package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.TransferOnDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.ReceiveTaskRequest;
import com.mflex.mwms.model.ShelfOnLocation;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TransferOnDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;

    @BindView(R.id.stv_ShelfLocation)
    EditText stvShelfLocation;

    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;

    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_save)
    Button buttonSave;

    @BindView(R.id.lvTaskDetailList)
    ListView lvTaskDetailList;

    MiniLoadingDialog mMiniLoadingDialog;

    List<TaskDetail> taskDetailList;

    private String taskNo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_on_detail);
        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");

        Intent intent = getIntent();
        Type listType = new TypeToken<ArrayList<TaskDetail>>() {
        }.getType();
        taskDetailList = (List<TaskDetail>) JsonUtil.fromJson(intent.getStringExtra("taskDetail"), listType);
        taskNo = intent.getStringExtra("taskNo");

        TransferOnDetailAdapter transferOnDetailAdapter = new TransferOnDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(transferOnDetailAdapter);

        stvTaskNo.setFocusable(false);
        stvTaskNo.setText(taskNo);

        stvBoxNumber.setOnKeyListener(this);
        stvShelfLocation.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonSave.setOnClickListener(this);

        stvShelfLocation.requestFocus();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_save:
                saveButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
                case R.id.stv_BoxNumber:
                    CheckBoxNumber(view);
                    break;
                case R.id.stv_ShelfLocation:
                    cheShelfLocation(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    private void CheckBoxNumber(View view) {
        if (StringUtils.isEmpty(stvShelfLocation.getText().toString())) {
            MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, "库位未输入");
            stvShelfLocation.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvShelfLocation.requestFocus();
                }
            }, 200);
            return;
        }

        boolean flag = false;
        boolean existFlag = false;
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName()) && taskDetail.checked) {
                existFlag = true;
                break;
            }
        }
        if (existFlag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号已在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, "箱号已在列表中");
            stvBoxNumber.setText("");
            return;
        }
        for (TaskDetail taskDetail : taskDetailList) {
            if (StringUtils.equals(stvBoxNumber.getText().toString(), taskDetail.getDetailName())) {
                flag = true;
                taskDetail.setChecked(true);
//                break;
            }
        }
        if (!flag) {
//            new MaterialDialog.Builder(view.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱号不在列表中")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, "箱号不在列表中");
            stvBoxNumber.setText("");
            return;
        }
        TransferOnDetailAdapter transferOnDetailAdapter = new TransferOnDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(transferOnDetailAdapter);
        stvBoxNumber.setText("");
        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        }, 200);
    }

    /**
     * 入库库位检查
     *
     * @param view
     */
    private void cheShelfLocation(View view) {
        if (StringUtils.isEmpty(stvShelfLocation.getText().toString())) {
            return;
        }
        mMiniLoadingDialog.show();
        XHttp.get("api/Task/ReceiveTransferLocationCheck")
                .params("WarehouseName", MMKVUtils.getString("Warehose", ""))
                .params("LocationName", stvShelfLocation.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<ShelfOnLocation>, ShelfOnLocation>(new SimpleCallBack<ShelfOnLocation>() {
                    @Override
                    public void onSuccess(ShelfOnLocation response) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.requestFocus();

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvShelfLocation.setText("");
                        stvShelfLocation.requestFocus();
                        MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, e);
                    }
                }) {
                });
    }

    private void clearButtonMd(View v) {
        stvBoxNumber.setText("");
        stvShelfLocation.setText("");
        stvShelfLocation.requestFocus();
        taskDetailList = new ArrayList<>();
        TransferOnDetailAdapter transferOnDetailAdapter = new TransferOnDetailAdapter(this, taskDetailList);
        lvTaskDetailList.setAdapter(transferOnDetailAdapter);
    }

    private void saveButtonMd(View v) {
        if (StringUtils.isEmpty(stvShelfLocation.getText().toString())) {
            MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, "库位未输入");
            stvShelfLocation.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvShelfLocation.requestFocus();
                }
            }, 200);
            return;
        }

        boolean flag = false;
        for (TaskDetail taskDetail : taskDetailList) {
            if (!taskDetail.isChecked()) {
                flag = true;
            }
        }
        if (flag) {
//            new MaterialDialog.Builder(v.getContext())
//                    .iconRes(R.drawable.icon_warning)
//                    .title(R.string.tip_warning)
//                    .content("箱包号没有全部扫描")
//                    .positiveText(R.string.lab_submit)
//                    .show();
            MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, "箱包号没有全部扫描");
            return;
        }
        ReceiveTaskRequest receiveTaskRequest = new ReceiveTaskRequest();
        receiveTaskRequest.setTaskNo(taskNo);
        receiveTaskRequest.setLocationName(stvShelfLocation.getText().toString());
        receiveTaskRequest.setCurrentWareHouse(MMKVUtils.getString("Warehose", ""));

        mMiniLoadingDialog.show();
        XHttp.post("api/Task/ReceiveTransferTask")
                .upJson(JsonUtil.toJson(receiveTaskRequest))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        XToastUtils.success("调拨确认成功", 2500);

                        setResult(0);
                        finish();

                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvBoxNumber.setText("");
                        stvBoxNumber.requestFocus();
//                        if (e.getCode() == 100) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_warning)
//                                    .title(R.string.tip_warning)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
//                        if (e.getCode() == 200) {
//                            new MaterialDialog.Builder(v.getContext())
//                                    .iconRes(R.drawable.icon_tip)
//                                    .title(R.string.tip_infos)
//                                    .content(e.getMessage())
//                                    .positiveText(R.string.lab_submit)
//                                    .show();
//                        }
                        MessageUtils.errorMsgAndVoice(TransferOnDetailActivity.this, e);
                    }
                }) {
                });
    }
}